package com.huawei.csi.tool.validation;

import com.huawei.csi.tool.config.LicenseConfig;
import com.huawei.csi.tool.util.FileUtil;
import com.huawei.csi.tool.util.JsonUtil;
import info.debatty.java.stringsimilarity.JaroWinkler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * license 校验
 */
public class LicenseVerify extends AbstractVerify {
    /**
     * LOGGER
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(LicenseVerify.class);

    /**
     * INSTANCE
     */
    private static final LicenseVerify INSTANCE = new LicenseVerify();
    /**
     * LICENSE_CONFIG_MAP
     */
    private static final Map<String, LicenseConfig> LICENSE_CONFIG_MAP = new HashMap<>();

    static {
        LICENSE_CONFIG_MAP.putAll(JsonUtil.getLicenseConfig("json/license.json"));
    }

    private LicenseVerify() {
    }

    public static LicenseVerify getInstance() {
        return INSTANCE;
    }

    /**
     * 计算结果，保留两位小数
     *
     * @param divisor  除数
     * @param dividend 被除数
     * @return double
     **/
    private static BigDecimal divide(int divisor, int dividend) {
        return new BigDecimal(divisor).divide(new BigDecimal(dividend), 2, RoundingMode.HALF_UP);
    }

    @Override
    public boolean isVerifiedPassed(Path path) {
        verify(path);
        return isVerifiedPassed;
    }

    /**
     * 获取license文件莫名称
     *
     * @param path license文件的绝对路径
     * @return java.lang.String
     **/
    @Override
    public String verify(Path path) {
        LOGGER.info("正在解析 license 文件，path= {} ", path);
        JaroWinkler jaroWinkler = new JaroWinkler();
        HashMap<String, BigDecimal> resultMap = new HashMap<>();
        List<String> stringList = FileUtil.getFileContentList(path);
        if (LICENSE_CONFIG_MAP.isEmpty()) {
            LOGGER.info("license 校验规则未配置，请确认文件是否存在！");
            return null;
        }
        for (Map.Entry<String, LicenseConfig> entry : LICENSE_CONFIG_MAP.entrySet()) {
            LicenseConfig config = entry.getValue();
            List<String> keyWords = config.getKeyWords();
            int matchCount = 0;
            for (String text : stringList) {
                // 遍历关键词列表
                for (String keyWord : keyWords) {
                    // 计算文本和关键词的相似度
                    double similarity = jaroWinkler.similarity(text, keyWord);
                    // 如果相似度大于或等于某个阈值，认为是匹配
                    if (similarity >= config.getMatch()) { // 这里的阈值可以根据需要调整
                        ++matchCount;
                    }
                }
            }
            resultMap.put(entry.getKey(), divide(matchCount, keyWords.size()));
        }
        Optional<String> maxKey = resultMap.entrySet()
                .stream()
                .max(Map.Entry.comparingByValue()) // 比较value
                .map(Map.Entry::getKey); // 获取key
        setVerifiedPassed(maxKey.isPresent());
        LOGGER.info("验证 license 完成，path= {}，验证结果 license ={}", path, maxKey.orElse(""));
        return maxKey.orElse("");
    }
}